package org.example.struct.array;

import com.alibaba.fastjson.JSON;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;

/**
 * @author liyishan
 * @date 2023/8/1 10:53
 * @apiNote
 */

public class Test00414ThirdMax {
    public static void main(String[] args) {
        int[] a = new int[]{0, 1,2,3,4};
        int count = test1(a);
        System.out.println(count + "  array:" + JSON.toJSON(a));
    }

    public static int test(int[] nums) {
        Arrays.sort(nums);
        Map<Integer,Integer> map = new HashMap<>();
        int size = 0;
        for(int i = 0 ;i<nums.length ;i++){
            if(!map.containsValue(nums[i])){
                map.put(size++,nums[i]);
            }
        }
        if(size <=2){
            return map.get(size-1);
        }else{
            return map.get(size-3);
        }
    }

    public static int test1(int[] nums){
        TreeSet<Integer> set = new TreeSet<>();
        for(int i=0;i<nums.length;i++){
            set.add(nums[i]);
            if(set.size() > 3){
                set.remove(set.first());
            }
        }
        return set.size() ==3 ? set.first():set.last();
    }


}
